package com.mofei.h003test.presenter;

import android.os.ParcelUuid;

import com.mofei.h003test.H003TestApplication;
import com.mofei.h003test.activity.MainActivity;
import com.polidea.rxandroidble2.RxBleClient;
import com.polidea.rxandroidble2.exceptions.BleScanException;
import com.polidea.rxandroidble2.scan.ScanFilter;
import com.polidea.rxandroidble2.scan.ScanResult;
import com.polidea.rxandroidble2.scan.ScanSettings;

import java.util.Date;
import java.util.Locale;
import java.util.concurrent.TimeUnit;

import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.disposables.Disposable;
import io.reactivex.functions.Action;
import io.reactivex.functions.Consumer;

/**
 * @author : timmy
 * @date : 2018/9/20
 */
public class MainActivityPresenter {
    private MainActivity mMainActivity;

    private RxBleClient mRxBleClient;
    private Disposable mScanSubscribe;
    private long mStartScanTime;


    private static final long SCANTIME = 10000;

    public MainActivityPresenter(MainActivity activity) {
        mMainActivity = activity;
        mRxBleClient = H003TestApplication.getRxBleClient(activity);
    }

    public void startScanDevice() {
        // 开始搜索设备
        ScanSettings settings = new ScanSettings.Builder()
                .setScanMode(ScanSettings.SCAN_MODE_LOW_LATENCY)
                .setCallbackType(ScanSettings.CALLBACK_TYPE_ALL_MATCHES)
                .build();

        // 配置扫描过滤规则
        ScanFilter.Builder builder = new ScanFilter.Builder();

        mStartScanTime = System.currentTimeMillis();

        ParcelUuid H003UUID = ParcelUuid.fromString("000056FF-0000-1000-8000-00805f9b34fb");

        // 扫描错误
        mScanSubscribe = mRxBleClient
                .scanBleDevices(settings, builder.setServiceUuid(H003UUID).build())
                .observeOn(AndroidSchedulers.mainThread())
                .doFinally(new Action() {
                    @Override
                    public void run() throws Exception {
                        stopScanDevice();
                    }
                })
                .subscribe(new Consumer<ScanResult>() {
                    @Override
                    public void accept(ScanResult scanResult) throws Exception {

                        // 添加到adapter中
                        mMainActivity.addScanResult(scanResult);
                        // 扫描完成
                        long currentTime = System.currentTimeMillis() - mStartScanTime;
                        if (currentTime >= SCANTIME) {
                            stopScanDevice();
                            mMainActivity.showToast("扫描完成");
                        }

                    }
                }, new Consumer<Throwable>() {
                    @Override
                    public void accept(Throwable throwable) throws Exception {
                        // 扫描错误
                        if (throwable instanceof BleScanException) {
                            handleBleScanException((BleScanException) throwable);
                        }
                    }
                });

    }

    private void stopScanDevice() {
        // 停止搜索设备
        if (mScanSubscribe != null) {
            mScanSubscribe.dispose();
            mScanSubscribe = null;
        }
    }


    private void handleBleScanException(BleScanException bleScanException) {
        final String text;

        switch (bleScanException.getReason()) {
            case BleScanException.BLUETOOTH_NOT_AVAILABLE:
                text = "蓝牙不支持";
                break;
            case BleScanException.BLUETOOTH_DISABLED:
                text = "请打开蓝牙后重试";
                break;
            case BleScanException.LOCATION_PERMISSION_MISSING:
                text = "On Android 6.0 location permission is required. Implement Runtime Permissions";
                break;
            case BleScanException.LOCATION_SERVICES_DISABLED:
                text = "位置服务需要打开";
                break;
            case BleScanException.SCAN_FAILED_ALREADY_STARTED:
                text = "Scan with the same filters is already started";
                break;
            case BleScanException.SCAN_FAILED_APPLICATION_REGISTRATION_FAILED:
                text = "Failed to register application for bluetooth scan";
                break;
            case BleScanException.SCAN_FAILED_FEATURE_UNSUPPORTED:
                text = "Scan with specified parameters is not supported";
                break;
            case BleScanException.SCAN_FAILED_INTERNAL_ERROR:
                text = "Scan failed due to internal error";
                break;
            case BleScanException.SCAN_FAILED_OUT_OF_HARDWARE_RESOURCES:
                text = "Scan cannot start due to limited hardware resources";
                break;
            case BleScanException.UNDOCUMENTED_SCAN_THROTTLE:
                text = String.format(
                        Locale.getDefault(),
                        "Android 7+ does not allow more scans. Try in %d seconds",
                        secondsTill(bleScanException.getRetryDateSuggestion())
                );
                break;
            case BleScanException.UNKNOWN_ERROR_CODE:
            case BleScanException.BLUETOOTH_CANNOT_START:
            default:
                text = "Unable to start scanning";
                break;
        }
        mMainActivity.showToast(text);
    }

    private long secondsTill(Date retryDateSuggestion) {
        return TimeUnit.MILLISECONDS.toSeconds(retryDateSuggestion.getTime() - System.currentTimeMillis());
    }

    public void onPause() {
        stopScanDevice();
    }

    public void connectDevice() {

    }
}
